package com.srwl.mytx.widget;

import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.activity.BaseActivity;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.CommentAdapter;
import com.srwl.mytx.domain.Comment;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.CommentService;
import com.srwl.mytx.activity.UserProfileActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@Deprecated
public class ForwardCommentListView extends RecyclerView {
    private static final String TAG = "CommentListView";
    private CommentAdapter commentAdapter;
    private List<Comment> commentList = new ArrayList<>();
    private int commentPage = 1;
    private boolean hasNextCommentPage = true;//是否还有更多评论的标记
    private static final int QUERY_SIZE = 10;
    private String topicId;
    private String uId;
    private Context context;
    private InteractionListener listener;
    private boolean hadPraise;//自己是否对该主题点过赞
    private Map praiseRecord;//以及被我点赞记录
    private Map commentPraiseSize;//点赞数量
    private int currentSelectCommentItemPosition;
    private Comment targetComment;

    public ForwardCommentListView(Context context) {
        super(context);
        this.context = context;
        initCommentAdapter();
    }

    public ForwardCommentListView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        initCommentAdapter();
    }


    private void initCommentAdapter() {
        commentAdapter = new CommentAdapter(context, commentList);
        setLayoutManager(new LinearLayoutManager(context, RecyclerView.VERTICAL, false));
        setAdapter(commentAdapter);
        setNestedScrollingEnabled(false);
        setFocusableInTouchMode(false);
        commentAdapter.setCommentClickListener(new CommentAdapter.CommentClickListener() {
            @Override
            public void commentItemLongClick(Comment comment) {
                showBottomDialog(comment);
            }

            @Override
            public void avatarClick(User targetUser) {
                context.startActivity(new Intent(context, UserProfileActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, targetUser));
            }

            @Override
            public void commentItemClick(Comment parentComment, int position) {
                Comment childComment = new Comment();
                //1表示是这是一条子评论
                childComment.setType(Constant.COMMENT_TYPE_CHILD);
                childComment.setTopicId(topicId);
                childComment.setParentId(parentComment.getId());
                childComment.setFromUid(UserProfileManager.getInstance().getLoginUserInfo().getuId());
                childComment.setFromAvatar(UserProfileManager.getInstance().getLoginUserInfo().getAvatar());
                childComment.setFromNick(UserProfileManager.getInstance().getLoginUserInfo().getUsername());
                currentSelectCommentItemPosition = position;
                targetComment = childComment;
                if (listener != null) {
                    listener.onCommentItemClick(parentComment.getFromNick());
                }
            }

            @Override
            public void childCommentItemClick(Comment parentComment, int position, User replyTarget) {
                Comment childComment = new Comment();
                //2表示是子评论的回复
                childComment.setType(Constant.COMMENT_TYPE_CHILD_REPLY);
                childComment.setTopicId(topicId);
                childComment.setParentId(parentComment.getId());
                childComment.setFromUid(UserProfileManager.getInstance().getLoginUserInfo().getuId());
                childComment.setFromAvatar(UserProfileManager.getInstance().getLoginUserInfo().getAvatar());
                childComment.setFromNick(UserProfileManager.getInstance().getLoginUserInfo().getUsername());
                childComment.setToUid(replyTarget.getuId());
                childComment.setToNick(replyTarget.getUsername());
                childComment.setToAvatar(replyTarget.getAvatar());
                currentSelectCommentItemPosition = position;
                targetComment = childComment;
                if (listener != null) {
                    listener.onCommentItemClick(parentComment.getFromNick());
                }
            }

            @Override
            public void addCommentPraise(Comment targetComment, final int position) {
                if (!Helper.getInstance().isNetworkConnected()) {
                    Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
                    return;
                }
                Map<String, Object> info = new HashMap<>();
                info.put("topicId", topicId);
                info.put("commentId", targetComment.getId());
                info.put("uId", UserProfileManager.getInstance().getLoginUserInfo().getuId());
                RetrofitManager.getInstance().createRequest(CommentService.class)
                        .commentPraise(info)
                        .enqueue(new Callback<CommonResult>() {
                            @Override
                            public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                                CommonResult result = response.body();
                                if (!response.isSuccessful() || result == null) {
                                    Log.e(TAG, "onResponse: " + response.message());
                                    return;
                                }
                                if (result.isError()) {
                                    Log.e(TAG, "onResponse: " + result.getMsg());
                                    return;
                                }

                                commentList.get(position).setHadPraise(true);
                                commentAdapter.notifyItemChanged(position);

                            }

                            @Override
                            public void onFailure(Call<CommonResult> call, Throwable t) {

                            }
                        });
            }

            @Override
            public void removeCommentPraise(Comment targetComment, int position) {

            }


        });
    }

    public void initCommentList(String topicId, String uId, InteractionListener listener) {
        commentList.clear();
        commentPage = 1;
        this.topicId = topicId;
        this.uId = uId;
        this.listener = listener;
        loadCommentData();

    }

    public void loadCommentData() {
        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, Object> info = new HashMap<>();
        info.put("topicId", topicId);
        info.put("uId", UserProfileManager.getInstance().getLoginUserInfo().getuId());
        info.put("page", commentPage);
        info.put("size", QUERY_SIZE);
        RetrofitManager.getInstance().createRequest(CommentService.class)
                .getComment(info)
                .enqueue(new Callback<CommonResult>() {

                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            if (listener != null) {
                                listener.onLoadCommentError();
                            }
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, result.getMsg());
                            if (listener != null) {
                                listener.onLoadCommentError();
                            }
                            return;
                        }
                        JSONObject jsonObject = (JSONObject) result.getData();

                        JSONObject pageInfo = jsonObject.getJSONObject("comments");
                        hasNextCommentPage = pageInfo.getBoolean("hasNextPage");
                        List<Comment> comments = pageInfo.getJSONArray("list").toJavaList(Comment.class);
                        // List<Comment> comments = JSONObject.parseArray(pageInfo.get("list").toString(), Comment.class);
                        Log.d(TAG, jsonObject.toJSONString());

                        if (commentPage == 1) {
                            hadPraise = jsonObject.getBoolean("hadPraise");
                            //  commentSize += jsonObject.getIntValue("commentSize");
                            // praiseSize += jsonObject.getIntValue("praiseSize");
                            if (comments.size() != 0) {


                                //以此来判别那些评论是被我点过赞
                                if (jsonObject.containsKey("praiseRecord")) {
                                    praiseRecord = JSONObject.parseObject(jsonObject.get("praiseRecord").toString(), Map.class);

                                }
                                if (jsonObject.containsKey("commentPraiseSize")) {

                                    commentPraiseSize = JSONObject.parseObject(jsonObject.get("commentPraiseSize").toString(), Map.class);
                                }
                            }

                            if (listener != null) {
                                listener.firstLoadDataComplete(hadPraise);
                            }
                        }
                        checkIsPraise(comments);
                        setupPraiseSize(comments);

                        commentList.addAll(comments);
                        commentAdapter.notifyDataSetChanged();
                        commentPage++;
                        if (listener != null) {
                            listener.onLoadCommentSuccess(hasNextCommentPage);
                        }

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        //  commentFooter.setVisibility(View.GONE);
                        if (listener != null) {
                            listener.onLoadCommentError();
                        }
                        Log.e(TAG, t.getMessage());

                    }
                });
    }

    public void prepareReplyTopic() {
        targetComment = new Comment();
        //0表示是一条普通评论，针对主题的评论
        targetComment.setType(Constant.COMMENT_TYPE_NORMAL);
        targetComment.setTopicId(topicId);
        targetComment.setFromUid(UserProfileManager.getInstance().getLoginUserInfo().getuId());
        targetComment.setFromAvatar(UserProfileManager.getInstance().getLoginUserInfo().getAvatar());
        targetComment.setFromNick(UserProfileManager.getInstance().getLoginUserInfo().getUsername());

    }

    public void commitComment(String content) {
        targetComment.setContent(content);
        if (targetComment.getType() == Constant.COMMENT_TYPE_NORMAL) {
            commitNormalComment();
        } else {
            commitChildComment();
        }

    }

    /**
     * 提交一个普通评论
     */
    private void commitNormalComment() {
        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        RetrofitManager.getInstance().createRequest(CommentService.class)
                .createComment_v1(targetComment)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            if (listener != null) {
                                listener.onCreateCommentError();
                            }
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, result.getMsg());
                            if (listener != null) {
                                listener.onCreateCommentError();
                            }
                            return;
                        }
                        String c_id = result.getData() + "";
                        targetComment.setId(c_id);
                        //把评论插到第一个的位置
                        commentList.add(0, targetComment);
                        commentAdapter.notifyDataSetChanged();
                        if (listener != null) {
                            listener.onCreateCommentSuccess();
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        if (listener != null) {

                            listener.showToast(context.getString(R.string.system_busy));
                        }
                    }
                });
    }


    /**
     * 创建子评论----就是评论中的回复
     */
    private void commitChildComment() {
        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        commentAdapter.setForbiddenItemClick(true);//添加子评论的时候，禁用 评论项的点击，避免位置错乱
        RetrofitManager.getInstance().createRequest(CommentService.class)
                .createChildComment(targetComment)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            if (listener != null) {
                                listener.onCreateCommentError();
                            }
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, result.getMsg());
                            if (listener != null) {
                                listener.onCreateCommentError();
                            }
                            return;
                        }
                        commentAdapter.addChildCommentComplete(currentSelectCommentItemPosition, targetComment, getChildViewHolder(getChildAt(currentSelectCommentItemPosition)));
                        if (listener != null) {
                            listener.onCreateChildCommentSuccess();
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        if (listener != null) {
                            listener.onCreateCommentError();
                        }
                        commentAdapter.setForbiddenItemClick(false);

                    }
                });
    }


    /**
     * 检查哪些评论被我点过赞，点过赞的给与标记
     *
     * @param comments
     */
    void checkIsPraise(List<Comment> comments) {
        //先进行非空判断，然后遍历，把被我赞过的评论，做好标记
        if (praiseRecord == null || praiseRecord.size() == 0) {
            return;
        }
        for (Object o : praiseRecord.keySet()) {
            for (Comment comment : comments) {
                if (comment.getId().equals(o)) {
                    comment.setHadPraise(true);
                }
            }
        }
    }


    /**
     * 设置评论的点赞数量
     *
     * @param comments
     */
    void setupPraiseSize(List<Comment> comments) {
        if (commentPraiseSize == null || commentPraiseSize.size() == 0) {
            return;
        }
        for (Object o : commentPraiseSize.keySet()) {
            for (Comment comment : comments) {
                if (comment.getId().equals(o)) {
                    comment.setPraiseSize(Integer.valueOf(commentPraiseSize.get(o).toString()));
                }
            }
        }
    }


    private void showBottomDialog(final Comment target) {
        final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(context, R.style.BottomDialog);
        View view = LayoutInflater.from(context).inflate(R.layout.comment_bottom_dialog, null);
        view.findViewById(R.id.rl_accusation).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog.dismiss();
                accusationComment(target);

            }
        });
        view.findViewById(R.id.rl_cancle).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog.dismiss();
            }
        });
        bottomSheetDialog.setContentView(view);
        bottomSheetDialog.show();
    }

    /**
     * 举报评论
     *
     * @param comment
     */
    void accusationComment(Comment comment) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) context).showToast_v1(context.getString(R.string.network_anomalies));
            return;
        }
        if (listener != null) {
            listener.showProgressBar(true);
        }
        RetrofitManager.getInstance().createRequest(CommentService.class)
                .accusationComment(comment.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (listener != null) {
                            listener.showProgressBar(false);
                        }
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            if (listener != null) {
                                listener.showToast(context.getString(R.string.system_busy));
                            }
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            if (listener != null) {
                                listener.showToast(context.getString(R.string.system_busy));
                            }
                        }
                        Log.d(TAG, "onResponse: 举报完成");

                        if (listener != null) {
                            listener.showToast(context.getString(R.string.accusation_complete));
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (listener != null) {
                            listener.showProgressBar(false);
                        }
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }


    public void setListener(InteractionListener listener) {
        this.listener = listener;
    }

    public interface InteractionListener {

        void onLoadCommentSuccess(boolean hasNextCommentPage);

        void onLoadCommentError();

        void showToast(String message);

        void firstLoadDataComplete(boolean hadPraise);

        void onCreateCommentSuccess();

        void onCreateChildCommentSuccess();

        void onCreateCommentError();

        void showProgressBar(boolean isShowProgressBar);

        void onCommentItemClick(String hint);
    }

}
